package com.jerry.provider.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jerry.common.bean.Product;
import com.jerry.provider.service.ProductService;

@RestController
@RequestMapping("/product")
public class ProductController {
	
	@Autowired
	private ProductService productService;
	@Autowired
	private DiscoveryClient client;

	//查询产品列表
	@GetMapping("/list")
	public List<Product> list() {
		ServiceInstance instance = client.getLocalServiceInstance();
		List<Product> productList = productService.list();
		for (Product product : productList) {
			product.setHost(instance.getHost());
			product.setPort(instance.getPort());
			product.setServerId(instance.getServiceId());
			System.out.println("provider === product === "+product);
		}
		return productList;
	}
	
	//根据id查询产品
	@GetMapping("/get/{id}")
	public Product get(@PathVariable("id") Long id) {
		ServiceInstance instance = client.getLocalServiceInstance();
		Product product = productService.get(id);
		product.setHost(instance.getHost());
		product.setPort(instance.getPort());
		product.setServerId(instance.getServiceId());
		System.out.println("provider === product === "+product);
		return product;
	}
	
	//增加产品
	@PostMapping("/add")
	public boolean add(@RequestBody Product product) {
		return productService.add(product);
	}

	//更新产品
	@PostMapping("/update")
	public boolean update(@RequestBody Product product) {
		return productService.update(product);
	}

	//删除产品
	@DeleteMapping("/delete/{id}")
	public void delete(@PathVariable("id") Long id) {
		productService.delete(id);
	}

}
